<template>
  <div class="add">
  <el-tabs v-model="activeName" @tab-click="handleClick" :before-leave='bfclick' stretch style="width:100%;">
        <!--one商品分类-->
    <el-tab-pane label="商品分类" name="first">
       <el-cascader-panel ref="cascaderRef" :props="caprops"  v-model="classV" @change="AhandleChange"></el-cascader-panel>
       
       <div class="hd_x" v-if="rclass">
            <div class="hd_t">已选中分类:</div>
            <el-tag class="hd_r" effect="plain" >{{ rclass }}</el-tag>
       </div>
        <div class="hd_x">
            <div class="hd_t">选中分类才能进行下一步:</div>
            <el-button type="primary" @click="nextA" class="hd_r">下一步</el-button>
       </div>
       <!-- <el-cascader ></el-cascader> -->
    </el-tab-pane>
        <!--two商品基本信息-->
    <el-tab-pane label="商品基本信息" name="second">
        <el-card class="add-container">
              <el-form :model="goodForm" :rules="rules" ref="goodRef" label-width="100px" class="goodForm">
                <el-form-item required label="已选分类">
                  <!-- <el-input style="width: 400px" v-model="goodForm.rclass" readonly disabled></el-input> -->
                   <el-cascader style="width:400px;" :props="caprops" :disabled="true" v-model="classV" ></el-cascader>
                </el-form-item>
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input style="width: 400px" v-model="goodForm.goodsName" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item required label="商品属性">
                  产地(必选)：<el-cascader ref='areaDialog' :props="adprops" v-model="goodForm.area" @change="handleChangeArea" placeholder="请选择地区"></el-cascader>
                  品牌(可选)： <el-select v-model="goodForm.brand" placeholder="选择品牌">
                  <el-option
                     v-for="item in brands" :key="item.id"
                    :value="item.id"
                    :label="item.name"
                    >
                  </el-option>
                </el-select>
                </el-form-item>
                <el-form-item v-for="(item,index) in sxArr" :key="index" label="商品属性">
                   {{item.name}}(可选)：
                  <el-checkbox-group v-if="item.isType==1" v-model="goodForm[item.id]">
                    <el-checkbox border v-for="(sitem,sindex) in item.child" :label="sitem.cop" :key="sindex">{{sitem.name}}</el-checkbox>
                  </el-checkbox-group>
                   <el-radio-group v-else v-model="goodForm[item.id]">
                    <el-radio v-for="(sitem,sindex) in item.child" :label="sitem.cop" :key="sindex">{{sitem.name}}</el-radio>
                  </el-radio-group> 
                </el-form-item>
                <el-form-item label="上架状态" prop="goodsSellStatus">
                  <el-radio-group v-model="goodForm.goodsSellStatus">
                    <el-radio label="1">上架</el-radio>
                    <el-radio label="0">下架 </el-radio>
                  </el-radio-group>
                </el-form-item>
                 <!-- 只能上传 jpg/png 文件 -->
                <el-form-item required label="商品轮播图" prop="goodsCoverImg">
                  
                  <el-upload
                       ref="upload"
                       list-type="picture-card"
                       accept="jpg,jpeg,png"
                       multiple
                      :show-file-list="false"
                      :action="uploadImgsServer"                                  
                      :before-upload="BhandleBeforeUpload"
                      :http-request="UploadFileMed">
                      <i class="el-icon-plus"></i>
                      <template #tip>
                         <ul class="el-upload-list el-upload-list--picture-card">
                        <li class="el-upload-list__item is-ready" v-for="(item,index) in fileShort" :key="index" style="margin:0 8px 8px 8px;">
                           <img class="el-upload-list__item-thumbnail" :src="item.imgUrl" alt="" />
                            <span class="el-upload-list__item-actions">
                              <span class="el-upload-list__item-delete" @click="handleRemoves(item)">
                                <i class="el-icon-delete"></i>
                              </span>
                            </span>
                        </li>
                      </ul>
                      </template>
                    </el-upload>
                    <!--  :auto-upload="false"  :file-list="fileList"-->
                </el-form-item>
                <el-form-item label="商品视频">
                  <el-upload
                     class="upload-demo"
                     ref="videoload"
                    :action="uploadVideoServer"
                    :http-request="UploadVideoMed"   
                    :file-list="videoList"
                    :auto-upload="false"
                    :limit="1"
                    >
                    <el-button size="small" type="primary">点击上传</el-button>

                  </el-upload>
                </el-form-item>
                <el-form-item required label="详情内容">
                  <div ref='editorElem' class="editors"></div>
                </el-form-item>
              </el-form>
               <div class="hd">
                <div class="hd_t">信息填写完成后请保存信息:</div>
                <el-button type="primary" @click="DsubmitAdd" class="hd_r">上传商品</el-button>
             </div>
          </el-card>
    </el-tab-pane>
    <!--three价格和库存-->
    <el-tab-pane label="价格库存" name="third">
          <el-card class="add-container">
             <!--1 规格-->
           <el-form label-width="120px" :model="formpt" inline>
             <el-form-item label="商品规格1(可选)">
                <el-select style="width: 150px;" v-model="formpt.gaValue" placeholder="添加商品规格" @change='ChandleSelecA'>
                  <el-option
                     v-for="item in options" :key="item.value"
                    :value="item.value"
                    :label="item.label"
                    :disabled="item.disabled"
                    >
                  </el-option>
                </el-select>
             </el-form-item>
             <el-form-item >
                 <el-checkbox-group v-model="formpt.gga" @change='Cthrselet'>
                  <el-checkbox name="gga" border v-for="(item,index) in optiona" :label="item.cop" :key="index" :checked="item.checked">{{item.label}}</el-checkbox>    
                </el-checkbox-group>
             </el-form-item>
             <el-form-item >
               <el-input style="width: 150px;" v-model="formpt.newGga" placeholder="请输入规格值"></el-input>
             </el-form-item>
              <el-form-item >
               <el-button type="primary" @click="CthrAdda" plain>添加规格值</el-button>
             </el-form-item>
             <br />
             <el-form-item label="商品规格2(可选)">
                <el-select style="width: 150px;" v-model="formpt.gbValue" placeholder="添加商品规格" @change='ChandleSelecB'>
                  <el-option
                    v-for="item in options" :key="item.value"
                    :value="item.value"
                    :label="item.label"
                    :disabled="item.disabled"
                    >
                  </el-option>
                </el-select>
             </el-form-item>
             <!--:label="formpt.gbValue"-->
             <el-form-item >
                 <el-checkbox-group v-model="formpt.ggb" @change='Cthrselet'>
                  <el-checkbox name="ggb" border v-for="(item,index) in optionb" :label="item.cop" :key="index" :checked="item.checked">{{item.label}}</el-checkbox>
                </el-checkbox-group>
             </el-form-item>
             <el-form-item >
               <el-input style="width: 150px;" v-model="formpt.newGgb" placeholder="请输入规格值"></el-input>
             </el-form-item>
             <el-form-item >
               <el-button type="primary" @click="CthrAddb" plain>添加规格值</el-button>
             </el-form-item>
           </el-form>
           <!--2批量填充-->
           <div class="hd">
             <div class="hd_t">价格和库存:</div>
             <el-button type="primary" size="small" icon="el-icon-plus" @click="ChandleAdd" class="hd_r">添加拼团区间({{tuanNum}}/3)</el-button>
          </div>
          <div class="hd">批量设置,将数据批量填充到下方表格</div>
          <el-form  :model="formct" inline>
             <el-form-item label="价格(元)">
               <el-input style="width: 150px;" type="number" :min="0" v-model="formct.price" placeholder="单行价格输入"></el-input>
             </el-form-item>
             <el-form-item label="库存">
               <el-input style="width: 150px;" type="number" :min="0" v-model="formct.store" placeholder="单行库存输入"></el-input>
             </el-form-item>
              <el-form-item >
               <el-button type="primary" icon="el-icon-circle-plus" @click="ConBatch">立即填充</el-button>
             </el-form-item>
             <br />
              <el-form-item label="商品市场价" required>
               <el-input style="width: 250px;" type="number" :min="0" v-model="formct.sprice" placeholder="商品市场价要高于商品价格"></el-input>
             </el-form-item>
           </el-form>

           <!--3 表格-->
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" border  height="350" style="width: 100%" :span-method="objectSpanMethod">
              <el-table-column prop="tuanNum" label="团人数" required>
                <template #default="scope">
                  <el-input type="number" :min="1" v-model="scope.row.tuanNum" placeholder="请输入团人数"></el-input>
                  <div v-if="scope.row.limitNum>0"  class="xbuy">每人限购{{scope.row.limitNum}}份</div>
                </template>
              </el-table-column>
              <el-table-column prop="tuanGg" label="规格"></el-table-column>
              <el-table-column prop="pinPrice" label="价格(元)">
                  <template #default="scope">
                   <el-input type="number" :min="0" v-model="scope.row.pinPrice" placeholder="请输入价格">￥</el-input>
                </template>
              </el-table-column>
              <el-table-column  prop="store" label="商品库存" >
                <template #default="scope">
                   <el-input type="number" :min="0" v-model="scope.row.store" placeholder="请输入库存"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="商品图片" width="150px" >
                <template #default="scope">              
                     <div v-if="scope.row.tuanI==0">
                        <img v-if="scope.row.productImg" :src="scope.row.productImg" class="avatar">
                        <el-button v-else size="small" type="primary" @click="uploadDio(scope.row.order)">点击上传</el-button>
                     </div>
                      <div v-else>
                        <img v-if="scope.row.productImg" :src="scope.row.productImg" class="avatar">
                     </div>
                  <!-- <img style="width: 100px; height: 100px;" :key="scope.row.goodsId" :src="scope.row.goodsImg" alt="商品主图"> -->
                </template>
              </el-table-column>
              <el-table-column label="操作" >
                <template #default="scope">
                  <el-row>
                   <el-button type="primary" @click="setBuy(scope.row.tuanI)" size="small" plain style="margin-bottom:5px;">设置限购</el-button>              
                   <el-button type="danger" v-if="scope.row.tuanI!=0" @click="handleDelete(scope.row.tuanI)" size="small" plain>删除</el-button>
                 </el-row>                
                </template>
              </el-table-column>
            </el-table>   
            <div class="hd hdh">
             <div class="hd_t">表格信息填写完成后请保存信息:</div>
             <el-button type="primary" @click="DsubmitAdd" class="hd_r">上传商品</el-button>
          </div>
             <DialogAddImg ref='addImg' :parent_id="parent_id" :reload="setImg" /> 
          </el-card>
    </el-tab-pane>
     <!--four运费和地区-->
    <el-tab-pane label="自提服务和运费" name="fourth">
      <el-card class="add-container">
        <!--1-->
         <div class="hd">拼团商品均为包邮商品</div>
         <!--2-->
          <el-form :model="formdt" label-width="150px" inline>
            <el-form-item label="是否选择不可售地区">
              <el-switch v-model="formdt.areaShow" active-color="#13ce66" :width="50"></el-switch>
              <el-tree v-show="formdt.areaShow"
                :props="Dprops"
                :load="DloadNode"
                :default-checked-keys="treeArr"
                node-key="value"
                ref="tree"
                lazy
                show-checkbox>
              </el-tree>
            </el-form-item>
            <br />
             <el-form-item label="商品自提">
               <el-switch v-model="formdt.ziShow" :width="50" @change="getZtArea"></el-switch>
            </el-form-item>
             <br /> 
             <el-form-item label="商品自提点" v-show="formdt.ziShow">
                <el-checkbox-group v-model="formdt.type">
                  <el-checkbox name="type" border v-for="(item,index) in optionArea" :label="item.value" :key="index" :checked="item.checked">{{item.label}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <br />
            <el-form-item label="商品标签">
               <el-checkbox-group v-model="formdt.label">
                  <el-checkbox name="label" border v-for="(item,index) in optionLabel" :label="item.cop" :key="index" :checked="item.checked">{{item.label}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
             <el-form-item >
                <el-button type="primary" @click="labelAdd" plain>添加商品标签</el-button>
            </el-form-item>
            <br />
            <!-- <el-form-item label="发货时间">
              <el-radio-group v-model="formdt.time">
                <el-radio label="当天发货"></el-radio>
                <el-radio label="48h发货"></el-radio>
              </el-radio-group>
            </el-form-item> -->
            <br />
             <!-- <el-form-item>
                  <el-button type="primary" @click="DsubmitAdd">上传商品</el-button>
             </el-form-item> -->
           </el-form> 
            <div class="hd hdh">
             <div class="hd_t">表格信息填写完成后请保存信息:</div>
             <el-button type="primary" @click="DsubmitAdd" class="hd_r">上传商品</el-button>
          </div>
      </el-card>
    </el-tab-pane>
  </el-tabs>
    
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance, inject } from 'vue'
import WangEditor from 'wangeditor'
import DialogAddImg from '@/components/DialogAddImg.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {randomString,getData,uploadFile,uploadVideo} from '@/utils/axios'
import { uploadImgsServer,uploadVideoServer } from '@/utils'
import { store } from '@/store'
export default {
  name: 'AddGood',
    components: { DialogAddImg},
  setup() {
    const { proxy } = getCurrentInstance()
    const $filters = inject('$filters')
    console.log('proxy', proxy)
    const cascaderRef=ref(null)
    const areaDialog=ref(null)
    const upload=ref(null)
    const videoload=ref(null)
    const editorElem = ref(null)
    const addImg=ref(null)
    const goodRef = ref(null)
    const tree = ref(null)
    const route = useRoute()
    const router = useRouter()
    //const { id } = route.query
    const state = reactive({
      goodId:'',
      busbaseId:store.getters.busId,
      activeName: 'first',
      bfclick:(activeName, oldActiveName)=>{
       if(state.classV==''){
         ElMessage.error({message:'请先选择商品分类',duration:1000})
         return false
       }
       if(state.classAble&&activeName=='first'){
         ElMessage.error({message:'修改商品不能修改分类',duration:1000})
         return false
       }
     },
      classAble:false,
      classV:'',
      classLast:'',
      rclass:'',
      caprops:{//获取分类列表
         lazy: true,
         lazyLoad(node, resolve) {
           const { level = 0, value } = node
            let parentId='';
            if(level!==0&&node.data){
                parentId=node.data.value;
            }
            getData('/common/common/getSkuGoodsCategoryHierarchyList',{parentId}).then(res=>{
                if(res.data.flag){
                const nodes = res.data.data.map(item=>({
                  value: item.id,
                  label: item.name,
                  leaf: item.childCount==0
                }))
                  return resolve(nodes)
                }
            }) 
        }
      },
       adprops:{
         lazy: true,
         lazyLoad(node, resolve) {
            let parentId='';
            if(node.level!==0&&node.data){
                parentId=node.data.value;
            }
            getData('common/common/getAreaHierarchyList',{parentId}).then(res=>{
                if(res.data.flag){
                const nodes = res.data.data.map(item=>{
                let leaf=item.areaCode%100==0?false:true // false是有子节点
                return  {
                    value: item.id,
                    label: item.name,
                    leaf: leaf
                    }
                })
                  return resolve(nodes)
                }
            }) 
        }
      },
      uploadImgsServer,
      uploadVideoServer,
      goodForm: {
        goodsName: '',
        area:[],
        brand:'',
        goodsSellStatus: '1',
        goodsCoverImg: '',
      },
      rules: {
        goodsName: [
          { required: 'true', message: '请填写商品名称', trigger: ['change'] }
        ],
      },
      areaName:'',//产地名称
      sxArr:[],//属性数组
      goodsAttr:[],
      brands:[],//品牌数组
      fileShort:[],
      videoList:[],
       html: '',//富文本编辑器
       text: '',//富文本编辑器
      formpt:{
        gaValue:'',
        gbValue:'',
        newGga:'',
        newGgb:'',
        gga:[],
        ggb:[],
      },
      formct:{
        price:'',
        store:'',
        sprice:''
      },
      tlength:0,
      isSpecial:0,
      options: [],
      newOptins:[],
      optiona:[],
      optionb:[],
      nameA:'',
      nameB:'',
      tuanNum:0,//团份数
      gg:[],//规格组合数组
      tableData:[],//表格数组
      tableArr:[],
      parent_id:0,
      
      optionArea:[],
      optionLabel:[],
      Dprops:{
          label: 'name',
          children: 'zones',
          isLeaf: 'leaf'
        }, 
     
      formdt: {
         areaShow:false,
          ziShow: false,
          type: [],
          label:[],
          time: ''
        },
       treeArr:[],
    })

    let editor
    onMounted(() => {
      editor = new WangEditor(editorElem.value)
      editor.config.pasteFilterStyle = false//关闭粘贴样式的过滤
     // editor.config.colors = ['#000000','#eeece0','#1c487f','#4d80bf']//配置颜色
      editor.config.uploadImgServer = uploadImgsServer//配置图片接口
      editor.config.uploadImgMaxLength = 9 // 一次最多上传 9 个图片
      editor.config.customUploadImg = function (resultFiles, insertImgFn) {//自己实现上传图片函数 
      //resultFiles 是 input 中选中的文件列表 insertImgFn 是获取图片 url 后，插入到编辑器的方法 上传图片，返回结果，将图片插入到编辑器中
      //console.log(resultFiles)
       resultFiles.forEach(item=>{
          uploadFile(item,uploadImgsServer).then(res=>{
                       // console.log(res.data)
                        if(res.data.data.length>0){
                          let imgUrl=$filters.prefix(res.data.data[0].imgUrl)
                          insertImgFn(imgUrl)
                    }
             })
       })
       }
      Object.assign(editor.config, {
            onchange(text) {
                console.log(text);
            },
      });
      editor.create();
      //如果有id，就是修改商品

      if(route.query.hasOwnProperty('id')){
        state.goodId=route.query.id;
        getData('/goods/goodsBus/getGoodsPinTuanDetail',{busbaseId:state.busbaseId,goodsId:state.goodId}).then(res=>{
            console.log('商品详情',res.data)
          if(res.data.flag){
             let data=res.data.data;
             state.activeName='second';
             state.classV=data.goods.goodsCategoryId.split(',');
             state.classLast=state.classV[state.classV.length-1];
             state.classAble=true;//表示是修改商品的标志
              let isMarketable=data.goods.isMarketable?'1':'0';
             state.goodForm={
               goodsName:data.goods.name,
               area:data.goods.areaId.split(','),
               brand:data.goods.brandId,
               goodsSellStatus:isMarketable
             }
             state.areaName=data.goods.areaName;
             state.fileShort=JSON.parse(data.goodsExtend.goodsImageList)
             
             data.attrRelList.forEach(item=>{//可选属性
               state.goodsAttr.push({id:item.attributeId,name:item.attributeName})
             })
             //第三步信息
             if(data.useSkuListFlag)//有规格
             {    state.isSpecial=1//规格属性
                  let skuA=data.useSkuList[0].skuList;
                  state.formpt.gaValue=skuA[0].parentId;
                  state.nameA=skuA[0].propertyName;
                  skuA.forEach(item=>{
                   let citem={value:item.propertyValueId,label:item.propertyValueName,checked:true,cop:JSON.stringify({value:item.propertyValueId,label:item.propertyValueName})} 
                     state.optiona.push(citem)
                 })
                   getData('/common/sku/getSkuPropertyValueList',{propertyId:state.formpt.gaValue,isUse:1}).then(res=>{
                      if(res.data.flag&&res.data.data.length>0){     
                         let data=res.data.data;
                         data.forEach(item=>{
                          let citem={value:item.id,label:item.name,cop:JSON.stringify({value:item.id,label:item.name})} 
                          state.optiona.push(citem)
                      })
                      let   temp = {}, result = [];//最后的新数组 
                       state.optiona.forEach((item)=>{
                            if(!temp[item.value]){
                                result.push(item);
                                temp[item.value] = true
                            }
                        })
                       state.optiona=result;
                      }
                  }) 
                 if(data.useSkuList.length==2){
                    let skuB=data.useSkuList[1].skuList;
                    state.formpt.gbValue=skuB[0].parentId;
                    state.nameB=skuB[0].propertyName;
                    skuB.forEach(item=>{
                    let citem={value:item.propertyValueId,label:item.propertyValueName,checked:true,cop:JSON.stringify({value:item.propertyValueId,label:item.propertyValueName})} 
                      state.optionb.push(citem)
                  })
                  getData('/common/sku/getSkuPropertyValueList',{propertyId:state.formpt.gbValue,isUse:1}).then(res=>{
                      if(res.data.flag&&res.data.data.length>0){     
                         let data=res.data.data;
                         data.forEach(item=>{
                          let citem={value:item.id,label:item.name,cop:JSON.stringify({value:item.id,label:item.name})} 
                          state.optionb.push(citem)
                      })
                      let   temp = {}, result = [];//最后的新数组 
                       state.optionb.forEach((item)=>{
                            if(!temp[item.value]){
                                result.push(item);
                                temp[item.value] = true
                            }
                        })
                       state.optionb=result;
                      }
                  }) 
                 }
             }
             state.formct.sprice=data.goods.cost/100
             state.tlength=data.pinSetList[0].pinSetDetail.length;
             state.tuanNum=data.pinSetList.length;
             for(let i=0;i<data.pinSetList.length;i++){
                 for(let j=0;j<data.pinSetList[i].pinSetDetail.length;j++){
                    let item=data.pinSetList[i].pinSetDetail[j];
                    let  valueNameA=data.productList[j].specificationValueStore.split(" ")[0]||''
                    let  valueNameB=data.productList[j].specificationValueStore.split(" ")[1]||''
                   state.tableData.push({
                    tuanNum:data.pinSetList[i].maxNum,
                    limitNum: data.pinSetList[i].limitNum,
                    tuanGg:data.productList[j].specificationValueStore,
                    productImg: item.productImg,
                    tuanI: i,
                    order: j,
                    pinPrice:item.pinPrice/100,
                    store: item.store,
                    tuanInCome: 0,
                    valueIdA:data.productList[j].specificationOne,
                    valueIdB:data.productList[j].specificationTwo,
                    valueNameA: valueNameA,
                    valueNameB: valueNameB})
              }
             }
            getBrandList()//获取品牌
            getSkuPropertyList()//获取规格
            getDetail(data.goodsExtend.textareaId,editor);
            //第四步信息
            state.treeArr=JSON.parse(data.gdsSaleArea.saleAreaJson)
            if(data.labelListFlag){
              for(let i=0;i<data.labelList.length;i++){
                let a={label:data.labelList[i].labelName,value:data.labelList[i].id,cop:JSON.stringify({label:data.labelList[i].labelName,value:data.labelList[i].id}),checked:true}
                 state.optionLabel.push(a)
              }
            }  
           if(data.zitiList){//自提点
                 state.formdt.ziShow=true;
                 let optionArea=[];
                 data.zitiList.forEach(item=>{
                    let a={label:item.zitiName,value:item.id}
                    optionArea.push(a)
                  })
                  let {busbaseId}=state;
                  getData('/goods/attr/getGdsZitiAddressByBusbaseId',{busbaseId,isUse:1}).then(res=>{
                        console.log(res.data)
                        if(res.data.flag&&res.data.data.length>0){
                          res.data.data.forEach(item=>{
                            let a={label:item.zitiName,value:item.id}
                            optionArea.push(a)
                          })
                           let   temp = {}, result = [];//最后的新数组 
                           optionArea.forEach((item)=>{
                                if(!temp[item.value]){
                                    result.push(item);
                                    temp[item.value] = true
                                }else{
                                  result.forEach(ele=>{
                                    if(ele.value==item.value){
                                       ele.checked=true
                                    }
                                  })
                                }
                            })
                          state.optionArea=result;
                          console.log(state.optionArea)
                        }
                    })
           }  
          }
       }) 
      
      }
    })
    onBeforeUnmount(() => {
      editor.destroy()
      editor = null
    })
    //方法类
    const handleClick=(tab, event) =>{//选项卡
       // console.log(tab);
      }
    // 第一步方法
    const AhandleChange = ( node ) => {//分类选择
      state.rclass=cascaderRef.value.getCheckedNodes()[0].pathLabels.join('/');
      state.classLast=node[node.length-1]
       ElMessage.success({message:`已选择分类`,duration:1000})
      getProperty()//获取属性
      getSkuPropertyList()//获取规格
     // getBusbaseLabel()//获取商品标签
      getBrandList()//获取品牌
    }
    const nextA=()=>{//下一步
        if(state.classV==''){
            ElMessage.error({message:'请先选择商品分类',duration:1000})
            return false
        }
        state.activeName='second';  
    }
    // 第二步方法
    const getDetail=(id,editor)=>{//获取富文本框
       getData('/common/common/getComTextAreaById',{sign:'111',id:id}).then(res=>{
            console.log('获取详情',res.data)
          if(res.data.flag){
             editor.txt.html(res.data.data.textArea)
          }
      }) 
    } 
    const handleChangeArea = ( node ) => {//返回最后的id值
      state.areaName='';
      if(node.length>0)
      {
        areaDialog.value.getCheckedNodes()[0].pathLabels.forEach(element => {//获取地址名称
              state.areaName+=element
         });
      }
    }
     const getProperty=()=>{//获取属性
       getData('/common/goodsAttribute/getSkuGoodsAttrListByCategoryId',{goodsCategoryId:state.classLast}).then(res=>{
            console.log('获取属性',res.data)
          if(res.data.flag&&res.data.data.length>0){
             res.data.data.forEach(ele => {
               if(ele.isType==1){
                 state.goodForm[ele.id]=[];
               }else{
                 state.goodForm[ele.id]='';
               }
               for(let i=0;i<ele.child.length;i++){
                 ele.child[i].cop=JSON.stringify({id:ele.child[i].id,name:ele.child[i].name})
               }
             });
              state.sxArr=res.data.data
          }
      }) 
     }
      const getBrandList=()=>{//获取品牌
       getData('/common/sku/getBrandListByGoodsCategoryId',{goodsCategoryId:state.classLast}).then(res=>{
            console.log('获取品牌',res.data)
          if(res.data.flag){
              state.brands=res.data.data
          }
      }) 
     }
     const BhandleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleRemoves=(file)=>{
       for(let i=0;i<state.fileShort.length;i++){
         if(state.fileShort[i].imgUrl==file.imgUrl){
           state.fileShort.splice(i,1)
           return;
         }
       }
    }   
    const UploadFileMed=(param)=>{//上传图片
      uploadFile(param.file,uploadImgsServer).then(res=>{
        console.log('商品上传',res.data)
        if(res.data.data.length>0){
          res.data.data[0].imgUrl=$filters.prefix(res.data.data[0].imgUrl)
          state.fileShort.push(res.data.data[0])
        }
       })
    }
    const UploadVideoMed=(param)=>{//上传视频
      console.log('视频上传',param)
      uploadVideo(param.file,uploadVideoServer).then(res=>{
        console.log(res.data)
        if(res.data.flag){
                
        }else{
          ElMessage.error('视频上传'+res.data.message)
        }
       })
    }
     // 第三步方法
     const getSkuPropertyList=()=>{//获取规格
       getData('/common/sku/getSkuPropertyList',{goodsCategoryId:state.classLast,isUse:1}).then(res=>{
            console.log('获取规格',res.data)
          if(res.data.flag&&res.data.data.length>0){
              state.options=[];
              res.data.data.forEach(item=>{
                 let citem={value:item.id,label:item.name,disabled:false} 
                if(item.id==state.formpt.gaValue||item.id==state.formpt.gbValue){
                    citem.disabled=true
                  }
                  state.options.push(citem)
              })
               
          }
      }) 
     }
    const setImg=(img,id)=>{//设置货品图片 id 是order
      state.tableData.forEach(item=>{
         if(item.order==id){
            item.productImg=img
           }
      })
      //state.tableData[id].productImg=img
    } 
    const uploadDio=(id)=>{//打开图片设置弹窗
      state.parent_id=id;
      addImg.value.open()
    }
    const setBuy=(tuanI)=>{//设置限购
        ElMessageBox.prompt('请输入限购份数', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:'number',
        }).then(({ value }) => {
          if(value>0&&Number.isInteger(value))
          {
            state.tableData.forEach(item=>{
              if(item.tuanI==tuanI){
                item.limitNum=value
              }
            })
          }
        }).catch(() => {});
    }
    const handleDelete=(tuanI)=>{//filter用于删除
      state.tableData=state.tableData.filter(item=>{
        return item.tuanI!=tuanI
      })
      state.tuanNum--;
    }
    const ChandleSelecA=(value)=>{//第一规格选择时改变规格值
      console.log(value)
        state.options.map(item=>{
          if(item.value==state.formpt.gbValue||item.value==value){
            item.disabled=true
          }else{
            item.disabled=false
          }
         if(item.value==value){
           state.nameA=item.label
         }
        })
        getData('/common/sku/getSkuPropertyValueList',{propertyId:value,isUse:1}).then(res=>{
            state.optiona=[];
          if(res.data.flag&&res.data.data.length>0){           
              res.data.data.forEach(item=>{
                   let citem={value:item.id,label:item.name,cop:JSON.stringify({value:item.id,label:item.name})} 
                     state.optiona.push(citem)
              })
          }
      }) 
      }
    const ChandleSelecB=(value)=>{
       state.options.map(item=>{
          if(item.value==state.formpt.gaValue||item.value==value){
            item.disabled=true
          }else{
            item.disabled=false
          }
           if(item.value==value){
           state.nameB=item.label
         }
        })
        getData('/common/sku/getSkuPropertyValueList',{propertyId:value,isUse:1}).then(res=>{
            console.log(res.data)
            state.optionb=[];
          if(res.data.flag&&res.data.data.length>0){
              res.data.data.forEach(item=>{
                   let citem={value:item.id,label:item.name,cop:JSON.stringify({value:item.id,label:item.name})} 
                     state.optionb.push(citem)
              })
               
          }
      }) 
     }
     const Cthrselet=()=>{//规格改变
      
      console.log(state.formpt.gga,state.formpt.gaValue)
      console.log(state.formpt.ggb,state.formpt.gbValue)
      changeTable();
     }
    const CthrAdda=()=>{//添加第一种规格
     if(state.formpt.gaValue==''){
       ElMessage.error({message:'请先选择第一类规格',duration:1500});
       return false
     }
     if(state.formpt.newGga!='')
      {
         let id=randomString(32);
         state.optiona.push({value:id,label:state.formpt.newGga,cop:JSON.stringify({value:id,label:state.formpt.newGga})})
         state.formpt.newGga='';
      }
    }
    const CthrAddb=()=>{//添加第二种规格
        if(state.formpt.gbValue==''){
          ElMessage.error({message:'请先选择第二类规格',duration:1500});
          return false
        }
        if(state.formpt.newGgb!='')
          {
            let id=randomString(32);
            state.optionb.push({value:id,label:state.formpt.newGgb,cop:JSON.stringify({value:id,label:state.formpt.newGgb})})
            state.formpt.newGgb='';
          }
        }
    const ChandleAdd = ()=>{//添加拼团区间
      if(state.tuanNum<3){
        state.tuanNum++;
         changeTable();
      }
     
    }
    const ConBatch=()=>{//批量添加
          console.log(state.formct)
          if(state.tableData.length>0){
            state.tableData.forEach(item=>{
              item.pinPrice=state.formct.price
              item.store=state.formct.store
            })
          }
        }
    const changeTable=()=>{//添加表格函数
          if(state.tuanNum>0){//当团份数大于0
            state.tableData=[];
            state.gg=[];//规格组合数组
           let gaArr=state.formpt.gga;
           let gbArr=state.formpt.ggb;
          if(gaArr.length>0||gbArr.length>0){//有第一种规格
            if(gaArr.length>0&&gbArr.length>0){//有第二种规格
              for(let i=0;i<gaArr.length;i++){
                for(let j=0;j<gbArr.length;j++){
                    let fag=JSON.parse(gaArr[i]);
                    let fbg=JSON.parse(gbArr[j])
                    let gname=`${fag.label} + ${fbg.label}`;
                    state.gg.push({gname,valueIdA:fag.value,valueNameA:fag.label,valueIdB:fbg.value,valueNameB:fbg.label})
                }
              }
            }else{//只有第一种规格
                if(gaArr.length>0){
                  gaArr.forEach(item=>{
                     let fag=JSON.parse(item);
                     state.gg.push({gname:fag.label,valueIdA:fag.value,valueNameA:fag.label,valueIdB:'',valueNameB:''})
                  }) 
                }else if(gbArr.length>0){
                  gbArr.forEach(item=>{
                    let fbg=JSON.parse(item);
                     state.gg.push({gname:fbg.label,valueIdA:'',valueNameA:'',valueIdB:fbg.value,valueNameB:fbg.label})
                  }) 
                }
            }
          }else{
            state.gg.push({gname:'',valueIdA:'',valueNameA:'',valueIdB:'',valueNameB:''})
          }
          state.tlength=state.gg.length;
          for(let i=0;i<state.tuanNum;i++){
              state.gg.forEach((item,index)=>{
                state.tableData.push({tuanNum:'',productImg:'',tuanGg:item.gname,valueIdA:item.valueIdA,valueNameA:item.valueNameA,valueIdB:item.valueIdB,valueNameB:item.valueNameB,tuanI:i,order:index,limitNum:0,tuanInCome:0,store:'',pinPrice:''})
              })
          }
        }
        console.log(state.tableData)
      }
    const objectSpanMethod=({row, column, rowIndex, columnIndex})=>{//合并行函数
         if (columnIndex === 0) {//第一列
            if (rowIndex %  state.tlength === 0) {
              return {
                rowspan:  state.tlength,//合并多少行
                colspan: 1 //合并多少列
              };
            } else {
              return {
                rowspan: 0,
                colspan: 0
              };
            }
        }
        if (columnIndex === 5) {//第五列
            if (rowIndex %  state.tlength === 0) {
              return {
                rowspan:  state.tlength,//合并多少行
                colspan: 1 //合并多少列
              };
            } else {
              return {
                rowspan: 0,
                colspan: 0
              };
            }
        }
    }
   // 第四步方法 
    const DloadNode=(node, resolve)=>{ 
      console.log(node)
      let parentId='';
       if(node.level!==0&&node.data){
          parentId=node.data.value;
      }
         getData('/common/common/getAreaHierarchyList',{parentId}).then(res=>{
            console.log(res.data)
               if(res.data.flag){
                const nodes = res.data.data.map(item=>{
                let leaf=item.areaCode%100==0?false:true // false是有子节点
                return  {
                    value: item.id,
                    name: item.name,
                    leaf: leaf
                    }
                })
                  return resolve(nodes)
              }
          })
    } 
    const getZtArea=(show)=>{//获取自提点
       if(show&&state.optionArea.length==0){
         let {busbaseId}=state;
         getData('/goods/attr/getGdsZitiAddressByBusbaseId',{busbaseId,isUse:1}).then(res=>{
              console.log(res.data)
              if(res.data.flag&&res.data.data.length>0){
                res.data.data.forEach(item=>{
                  let a={label:item.zitiName,value:item.id}
                  state.optionArea.push(a)
                })
              }
          })
       }
    }
    const labelAdd=()=>{//添加商品标签
        ElMessageBox.prompt('请输入商品标签', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType:'text',
        }).then(({ value }) => {
          value = value.replace(/^\s*|\s*$/g,"");
          if(value)
          { let id=randomString(32);
            let a={label:value,value:id,cop:JSON.stringify({label:value,value:id})}
            state.optionLabel.push(a)
          }
        }).catch(() => {});
    }
    const getBusbaseLabel=()=>{//获取商品标签
       let {busbaseId}=state;
       getData('/goods/attr/getBusbaseLabelByBusbaseId',{busbaseId,isUse:1}).then(res=>{
            console.log(res.data)
               if(res.data.flag){
               
              }
          })
    }
    const DsubmitAdd=()=>{
       //保存信息标志1
        state.html= editor.txt.html();
        console.log(state.fileShort)
         if(state.goodForm.goodsName==''){
           ElMessage.error({message:'请先填写商品名称',duration:1500})
           return false;
         }         
         if(state.goodForm.area.length<=0){
           ElMessage.error({message:'请先选择商品产地',duration:1500})
           return false;
         }
        if(state.fileShort.length<=0){
           ElMessage.error({message:'请先上传商品图片',duration:1500})
           return false;
         } 
        if(state.html==''){
           ElMessage.error({message:'请先填写详情内容',duration:1500})
           return false;
         }
      //保存信息标志2
      if(state.tuanNum==0){
        ElMessage.error({message:'请先添加拼团区间',duration:1500})
        return false;
      }  
     if(state.formct.sprice==''){
        ElMessage.error({message:'请填写商品市场价',duration:1500})
        return false;
      }    
      if(state.formdt.ziShow&&state.formdt.type.length<=0){
         ElMessage.warning({message: '自提商品至少选择一个自提点',duration:2000});
         return false;
      }
       console.log(state.tableData)
       console.log(state.formpt)
       let newA=state.tableData.map(item=>{return item.pinPrice})
       let maxP=Math.max(...newA)
       if(maxP>state.formct.sprice){
          ElMessage.error({message:'商品价格不能大于商品市场价',duration:1500})
          return false;
       }
       if(!state.classAble){//可选属性
            state.goodsAttr=[];
            state.sxArr.forEach(item=>{
                if(state.goodForm[item.id]!=''){
                  if(typeof state.goodForm[item.id]=='string'){//单选框
                      state.goodsAttr.push(JSON.parse(state.goodForm[item.id]))
                  }else{//多选框
                    state.goodForm[item.id].forEach(ele=>{
                      state.goodsAttr.push(JSON.parse(ele))
                    })
                  }
                }
            }) 
         }
       //找规格数组
       state.newOptins=[];
       state.formpt.gga.forEach((item,index)=>{
          item=JSON.parse(item)
          state.newOptins.push({'valueId':item.value,'valueName':item.label,'order':index+1,'grade':1,'parentId':state.formpt.gaValue,'name':state.nameA})
       })
      state.formpt.ggb.forEach((item,index)=>{
          item=JSON.parse(item)
          state.newOptins.push({'valueId':item.value,'valueName':item.label,'order':index+1,'grade':2,'parentId':state.formpt.gbValue,'name':state.nameB})
       })
      if(state.formpt.gga!=[]||state.formpt.ggb!=[]){//有规格
        state.isSpecial=1//规格属性
      }
     console.log(state.newOptins,state.tableData)
       //重新构造表格数组
       let tableArr=[];
       for(let i=0;i<state.tuanNum;i++){
         tableArr.push({startNum:0,endNum:0,limitNum:0,tuanInCome:0,goodsPinSetDetail:[]})
         for(let j=0;j<state.tableData.length;j++){
           if(state.tableData[j].tuanI==i){//在同一区间下
             if(state.tableData[j].order==0){
                if(state.tableData[j].tuanNum==''){
                    ElMessage.error({message:'请先添加团人数',duration:1500})
                     return false;
                }
                if(!Number.isInteger(Number(state.tableData[j].tuanNum))){
                    ElMessage.error({message:'团人数只能是正整数',duration:1500})
                     return false;
                }
                tableArr[i].startNum=state.tableData[j].tuanNum;
                tableArr[i].endNum=state.tableData[j].tuanNum;
                tableArr[i].limitNum=state.tableData[j].limitNum;
                tableArr[i].tuanInCome=state.tableData[j].tuanInCome;
             }
             let {productImg,valueIdA,valueNameA,valueIdB,valueNameB,order,store,pinPrice}=state.tableData[j]
             if(pinPrice==''||store==''){
                ElMessage.error({message:'请先补齐所以的价格和库存',duration:1500})
                return false;
             }
             pinPrice=Number(pinPrice)*100;
             tableArr[i].goodsPinSetDetail.push({productImg,valueIdA,valueNameA,valueIdB,valueNameB,order,store,pinPrice})
           }
         }
       }
      state.tableArr= tableArr;
      console.log(state.tableArr)
      let goodsCategoryId=state.classV.join(',');//分类id数组
      let areaId=state.goodForm.area.join(',');
      let isbalArr=tree.value.getCheckedKeys();//不可售地区
      let labelId='',labelName='',labelIdArr=[],labelNameArr=[];
      state.formdt.label.forEach((item)=>{
         let nItem=JSON.parse(item);
         labelIdArr.push(nItem.value)
         labelNameArr.push(nItem.label)
      })
     let goodsImage=state.fileShort.map((item,index)=>{
          return{'imgUrl':item.imgUrl,'order':index+1}
      })
      labelId=labelIdArr.join(",");
      labelName=labelNameArr.join(",");
      let marketPrice=Number(state.formct.sprice)*100;
      let zitiAddress=state.formdt.type.join(",")
      let goodsType=state.formdt.ziShow?2:1;
      let paras={
        loginName:store.getters.userName,//登录名
        busbaseId:state.busbaseId,//商户id
        cost:marketPrice,//成本价
        marketPrice:marketPrice,//市场价      
        name:state.goodForm.goodsName,//商品名称---
        isMarketable:state.goodForm.goodsSellStatus,//商品上下架状态
        goodsCategoryId:goodsCategoryId,//商品分类ID---
        isSpecial:state.isSpecial,// 1单规格 0无规格
        areaId:areaId,//产地ID---
        areaName:state.areaName,//产地名称---
        brandId:state.goodForm.brand,//品牌ID---
        description:state.html,//商品详细描述
        labelId:labelId,//商品标签ID,‘,’号分割 '1243244dsd432,1244234dsad432,1244234dsad432'
        labelName:labelName,//标签名称,‘,’号分割 '热销,精品,精品'
        zitiAddress:zitiAddress,//自提地址 '1243244dsd432,1244234dsad432,1244234dsad432'
        goodsImage:JSON.stringify(goodsImage),//商品主图全路径列表 数组转字符串
        saleArea:JSON.stringify(isbalArr),//不可售地区   数组转字符串
        specialSet:JSON.stringify(state.newOptins),//规格设置   数组转字符串
        goodsPinSet:JSON.stringify(state.tableArr),//拼团设置   数组转字符串
        goodsAttr:JSON.stringify(state.goodsAttr),//商品属性设置---
        deliveryTypeId:'28A7028708F44F1E88CC3DBF98B94D0D',//运费模板ID
        goodsType:goodsType,//1:物流商品，2自提商品，3:畅游通商品，4:门票商品', 默认：1
        goodsVideo:'',//视频路径
        metaKeywords:'',//商品自定义搜索关键字
        diyGoodsCategoryId:'',//自定义商品分类ID      
      }
      if(state.classAble){//修改商品
        paras.id=state.goodId;
       getData('/goods/goodsBus/updateGoods',paras).then(res=>{
              console.log(res.data)
              if(res.data.flag){
                ElMessage.success({message: '商品修改成功',duration:2000});
                router.push({ path: '/glist' })
              }else{
                ElMessage.error({message:res.data.message,duration:2000});
              }
          })
      }else{
        getData('/goods/goodsBus/addGoods',paras).then(res=>{
              console.log(res.data)
              if(res.data.flag){
                ElMessage.success({message: '商品添加成功',duration:2000});
                router.push({ path: '/glist' })
              }else{
                ElMessage.error({message:res.data.message,duration:2000});
              }
          })
      }
    }
    return {
      ...toRefs(state),
      cascaderRef,
      handleClick,
      AhandleChange,
      nextA,

      areaDialog,
      goodRef,
      upload,
      videoload,
      editorElem,
      getProperty,
      getDetail,
      BhandleBeforeUpload,
      handleRemoves,
      UploadFileMed,
      UploadVideoMed,
      handleChangeArea,

      addImg,
      setImg,
      setBuy,
      handleDelete,
      uploadDio,
      getSkuPropertyList,
      ChandleSelecA,
      ChandleSelecB,
      Cthrselet,
      CthrAdda,
      CthrAddb,
      ChandleAdd,
      ConBatch,
      objectSpanMethod,
     
       tree,
       DloadNode,
       DsubmitAdd,
       getZtArea,
       getBusbaseLabel,
       labelAdd,
    }
  }
}
</script>

<style scoped>
  .editors{z-index:1;position: relative;}
 .hd{overflow: hidden;height: 42px;}
 .hd_position{position: absolute;left:0;bottom:0;z-index: 99;right:0;}
 .hd_x{height:42px;margin-top:50px;}
 .hdh{padding-top: 10px;}
 .hd_t{font-weight: 550;float: left;line-height: 32px;}
 .hd_r{float: right;}
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar {
    width: 100px;
    height: 70px;
    display: block;
  }

  .xbuy{text-align: center;color: #409EFF;font-size: 14px;line-height: 30px;}
  .el-checkbox-group{display: inline-block;}
</style>